<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      选择车队经理下拉框-->
      <el-form-item label="车队经理" prop="facilitId">
        <el-select v-model="queryParams.mangerId"   placeholder="请选择车队经理" clearable>
          <el-option
            v-for="item in mangerList"
            :key="item.mangerId"
            :label="item.userName"
            :value="item.mangerId"
            @change="chooseManger(item.mangerId)"
          />
        </el-select>
      </el-form-item>

      <!--      选择车队长下拉框-->
      <el-form-item label="车队长" prop="facilitId">
        <el-select v-model="queryParams.leaderId"   placeholder="请选择车队长" clearable>
          <el-option
            v-for="item in leaderList"
            :key="item.leaderId"
            :label="item.userName"
            :value="item.leaderId"
            @change="chooseLeader(item.leaderId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="司机姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入司机用户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="plateNum">
        <el-input
          v-model="queryParams.plateNum"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>


        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--      数据区域-->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="5"><div class="grid-content bg-purple"><span>加注金额</span><h2>{{ cardData.totalOrderMoney }} 元</h2></div></el-col>
        <el-col :span="5"><div class="grid-content bg-purple"><span>加注体积</span><h2>{{cardData.totalOrderFilledKg}} 千克</h2></div></el-col>
        <el-col :span="5"><div class="grid-content bg-purple"><span>加注笔数</span><h2>{{cardData.totalTransactions}} 笔</h2></div></el-col>
        <el-col :span="9"><div class="grid-content bg-purple">
          <el-row :gutter="10">
            <el-col :span="11">
              <el-radio-group @change="changeOpt" v-model="radio1" >
                <el-radio-button label="全部"></el-radio-button>
                <el-radio-button label="今日"></el-radio-button>
                <el-radio-button label="本周"></el-radio-button>
                <el-radio-button label="本月"></el-radio-button>
              </el-radio-group>
            </el-col>
            <el-col :span="11">
              <el-date-picker @change="DateOpt"
                              v-model="value1"
                              type="date"
                              placeholder="选择日期时间">
              </el-date-picker>
            </el-col>
          </el-row>
        </div>
        </el-col>
      </el-row>
    </el-card>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['consumer:statistic:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="statisticList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="statisticId" />
      <el-table-column label="加注金额(元)" align="center" prop="orderMoney" />
      <el-table-column label="支付方式" align="center" prop="statisticType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.statistic_order_type" :value="scope.row.statisticType"/>
        </template>
      </el-table-column>
      <el-table-column label="车属公司" align="center" prop="companyName" />
      <el-table-column label="车牌号" align="center" prop="plateNum" />
<!--      <el-table-column label="加注单价(元)" align="center" prop="orderPrice" />-->
      <el-table-column label="加注体积(kg)" align="center" prop="orderFilled" />
      <el-table-column label="司机姓名" align="center" prop="userName" />
      <el-table-column label="设备名称" align="center" prop="facilitName" />
      <el-table-column label="加注位置" align="center" prop="userName" >
        <template slot-scope="scope">
          <el-button slot="append" icon="el-icon-location" @click="openMap(scope.row.facilitLat,scope.row.facilitLng)"></el-button>
          <MapSelect ref="ms"/>
        </template>
      </el-table-column>
      <el-table-column label="加注时间" align="center" prop="updateTime" />

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


  </div>
</template>

<script>
import {
  listStatistic,
  getStatistic,
  delStatistic,
  addStatistic,
  updateStatistic,
  getStatisticData
} from "@/api/consumer/statistic";
import MapSelect from "@/views/components/MapSelect.vue";
import {listFacilit} from "@/api/consumer/facilit";
import {listCompany} from "@/api/consumer/company";
import {getCompanyId, getFleetLeader, getFleetManager, listUser} from "@/api/consumer/user";
import {formatDate} from "@/utils";

export default {
  name: "Statistic",
  components: {MapSelect},
  dicts: ['statistic_order_type'],
  data() {
    return {
      //日期选择框数据
      value1: '',
      // 多选框选中数组
      radio1: '全部',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 统计总表格数据
      statisticList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 车队经理列表数据
      mangerList: [],
      // 公司车队长数据
      leaderList: [],
      //本公司id
      companyId: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        facilitId: null,
        fillerId: null,
        userId: null,
        userName: null,
        companyId: null,
        mangerId: null,
        leaderId: null,
        carId: null,
        plateNum: null,
        sn: null,
        orderFilled: null,
        orderMoney: null,
        orderPrice: null,
        statisticType: null,
        weixinOrderId: null,
        snNumber: null,
        facilitLat: null,
        facilitLng: null,
        facilitProvince: null,
        facilitCity: null,
        facilitArea: null,
        status: null,
        beginTime: null,
        endTime: null
      },
      //统计卡片数据
      cardData: {
        totalOrderMoney: 0,
        totalOrderFilledKg: 0,
        totalTransactions: 0
      },
//地图初始值
      mainForm: {
        address: '',
        lat: '',
        lng: '',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        facilitId: [
          { required: true, message: "加注机id编号不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户账号id编号,司机id不能为空", trigger: "blur" }
        ],
        sn: [
          { required: true, message: "设备唯一标识sn不能为空", trigger: "blur" }
        ],
        orderFilled: [
          { required: true, message: "已加注量(以毫升为单位)不能为空", trigger: "blur" }
        ],
        orderMoney: [
          { required: true, message: "支付总金额(单位:分)不能为空", trigger: "blur" }
        ],
        orderPrice: [
          { required: true, message: "单价(单位:分)不能为空", trigger: "blur" }
        ],
        statisticType: [
          { required: true, message: "订单类型1:公司钱包,2:个人钱包,3:微信不能为空", trigger: "change" }
        ],
      }
    };
  },
  async created() {
    try {
      await this.getList();
    } catch (error) {
      console.error('执行 created 钩子时出错：', error);
    }
  },


  methods: {
    /** 日期选择框改变*/
    DateOpt(val) {
      if (val === null) {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
        this.getList();
        return;
      }
      // 格式化日期
      var formatDate = function(date) {
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        return year + '-' + month + '-' + day;
      };
      // 将选定日期格式化为 "yyyy-MM-dd 00:00:00" 和 "yyyy-MM-dd 23:59:59"
      var selectedDate = new Date(val);
      var beginTime = formatDate(selectedDate) + ' 00:00:00';
      var endTime = formatDate(selectedDate) + ' 23:59:59';
      // 设置beginTime和endTime到this.queryParams中
      this.queryParams.beginTime = beginTime;
      this.queryParams.endTime = endTime;
      // 调用getList()方法
      this.getList();
      // 在控制台打印格式化后的日期
      console.log(this.queryParams.beginTime, this.queryParams.endTime);
    },


    // 获取今天时间间隔
    getTodayInterval() {
      var today = new Date();
      var beginTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
      var endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);
      this.queryParams.beginTime = formatDate(beginTime);
      this.queryParams.endTime = formatDate(endTime);
      return { beginTime: beginTime, endTime: endTime };
    },

    // 获取本周时间间隔
    getCurrentWeekInterval() {
      var today = new Date();
      var currentDay = today.getDay();
      var beginTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() - currentDay, 0, 0, 0);
      var endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + (6 - currentDay), 23, 59, 59);
      this.queryParams.beginTime = formatDate(beginTime);
      this.queryParams.endTime = formatDate(endTime);
      return { beginTime: beginTime, endTime: endTime };
    },

// 获取本月时间间隔
    getCurrentMonthInterval() {
      var today = new Date();
      var beginTime = new Date(today.getFullYear(), today.getMonth(), 1, 0, 0, 0);
      var endTime = new Date(today.getFullYear(), today.getMonth() + 1, 0, 23, 59, 59);
      this.queryParams.beginTime = formatDate(beginTime);
      this.queryParams.endTime = formatDate(endTime);
      return { beginTime: beginTime, endTime: endTime };
    },

    /**日周月改变*/
    changeOpt(val) {
      switch (val) {
        case '全部':
          this.reset();
          this.queryParams.beginTime = null; this.queryParams.endTime = null;
          break;
        case '今日':
          this.getTodayInterval();
          break;
        case '本周':
          this.getCurrentWeekInterval();
          break;
        case '本月':
          this.getCurrentMonthInterval();
          break;
      }
      this.getList();
    },

    getList() {
      this.loading = true;
      getCompanyId().then(response => {
        this.queryParams.companyId = response.data;
        Promise.all([
          listStatistic(this.queryParams),
          getFleetManager(this.queryParams.companyId),
          getFleetLeader(this.queryParams.companyId),
          this.getCardData(this.queryParams)
        ]).then(([statisticResponse, managerResponse, leaderResponse]) => {
          this.statisticList = statisticResponse.rows;
          this.total = statisticResponse.total;
          this.mangerList = managerResponse;
          this.leaderList = leaderResponse;

          this.loading = false; // 在所有异步请求都完成之后再将loading状态设置为false
        }).catch(error => {
          // 处理错误
          console.error('Error occurred:', error);
          this.loading = false; // 处理错误时也需要将loading状态设置为false
        });
      }).catch(error => {
        // 处理错误
        console.error('Error occurred:', error);
        this.loading = false; // 处理错误时也需要将loading状态设置为false
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        statisticId: null,
        facilitId: null,
        fillerId: null,
        userId: null,
        userName: null,
        companyId: null,
        mangerId: null,
        leaderId: null,
        carId: null,
        plateNum: null,
        sn: null,
        orderFilled: null,
        orderMoney: null,
        orderPrice: null,
        statisticType: null,
        weixinOrderId: null,
        snNumber: null,
        facilitLat: null,
        facilitLng: null,
        facilitProvince: null,
        facilitCity: null,
        facilitArea: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        facilitId: null,
        fillerId: null,
        userId: null,
        userName: null,
        companyId: null,
        mangerId: null,
        leaderId: null,
        carId: null,
        plateNum: null,
        sn: null,
        orderFilled: null,
        orderMoney: null,
        orderPrice: null,
        statisticType: null,
        weixinOrderId: null,
        snNumber: null,
        facilitLat: null,
        facilitLng: null,
        facilitProvince: null,
        facilitCity: null,
        facilitArea: null,
        status: null
      };
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.radio1 = '全部';
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.statisticId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加统计总";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const statisticId = row.statisticId || this.ids
      getStatistic(statisticId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改统计总";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.statisticId != null) {
            updateStatistic(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStatistic(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const statisticIds = row.statisticId || this.ids;
      this.$modal.confirm('是否确认删除统计总编号为"' + statisticIds + '"的数据项？').then(function() {
        return delStatistic(statisticIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('consumer/statistic/export', {
        ...this.queryParams
      }, `statistic_${new Date().getTime()}.xlsx`)
    },

    /**根据经纬度打开地图弹窗*/
    // 打开地图弹窗
    openMap(lat, lng) {
      if (lat === null || lng === null) {
        this.$message.error('经纬度为空');
        return;
      }
      this.$refs.ms.show();
      // 根据经纬度设置初始值
      this.mainForm.lat = lat;
      this.mainForm.lng = lng;
      this.$refs.ms.setLocationByLatLng(this.mainForm.lat, this.mainForm.lng);
      this.GeocoderAddress(this.mainForm.lat, this.mainForm.lng);
    },
    /**根据经纬度打开地图弹窗*/
    GeocoderAddress(lat, lng) {
      let that = this;
      that.geocoder = new qq.maps.Geocoder({
        complete: function (result) {
          var address = result.detail.addressComponents;
          that.form.stationProvince = address.province;
          that.form.stationCity = address.city;
          that.form.stationArea = address.district;
        }
      });
      that.geocoder.getAddress(new qq.maps.LatLng(lat, lng));
      //这里是反的,卧槽
      that.form.stationLatitude = lng;
      that.form.stationLongitude = lat;
    },

    /** 选择经理 */
    chooseManger(id) {
      this.queryParams.mangerId = id;
    },
    /** 选择车队长*/
    chooseLeader(id) {
      this.queryParams.leaderId = id;
    },

    /**获取统计卡片数据*/
    getCardData(query) {
      this.loading = true;
      getStatisticData(query).then(response => {
        this.cardData = response.data;
        this.loading = false;
      });
    }
  }
};
</script>

<style scoped>
.box-card {
  width: 100%;
  margin-bottom: 20px;
  margin-top: 20px;
}

.grid-content {
  text-align: center;
  padding: 20px;
}

@media screen and (max-width: 768px) {
  .el-row {
    flex-direction: column;
  }

  .el-col {
    width: 100%;
  }
}

/* 主要颜色和字体 */
.el-row {
}

.el-col {
  border-radius: 8px;
}

/* 浅色背景 */
.bg-light {
  background-color: #f5f5f5;
  color: #333333;
}

/* 深色背景 */
.bg-dark {
  background-color: #fafafa;
  color: #555555;
}

/* 网格内容样式 */
.grid-content {
  border-radius: 8px;
  padding: 20px;
  min-height: 50px;
}

/* 行背景 */
.row-bg {
  padding: 20px;
  background-color: #f5f5f5;
}

/* 媒体查询以实现响应式布局 */
@media screen and (max-width: 768px) {
  .el-row {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .el-col {
    width: 100%;
    margin-bottom: 20px;
  }
}

</style>
